package com.apes.framework.query.lib;

import com.apes.framework.jpa.generator.GeneratorUtil;
import com.apes.framework.jpa.generator.model.Sequence;
import com.apestech.api.tables.SequenceManage;
import com.apestech.api.tables.modul.SeqField;
import com.apestech.api.xml.esb.EsbUtil;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.sql.variable.SqlSection;
import com.apestech.framework.util.callback.IdKeyCallback;

import java.util.ArrayList;

/**
 * @author hup
 * @create 2020-03-02-18:34
 */
public class JPAId implements IdKeyCallback {

    private int padding;
    private String conId;
    private ArrayList< SeqField > seqlist;
    private SqlSession session;

    public JPAId(String conId, ArrayList< SeqField > seqlist, SqlSession session){
        this.conId=conId;
        this.seqlist=seqlist;
        this.session=session;
    }

    @Override
    public Object getKey(String tabName) throws Exception {
        SequenceManage sequenceManage=new SequenceManage(session);
        try {
            if(EsbUtil.getSeqmap().get(conId)==null){
                EsbUtil.getSeqmap().put(conId, 1);
                int len=seqlist.size();
                for(int i=0; i<len; i++){
                    if(tabName.equals(seqlist.get(i).getTableId())){
                        padding=seqlist.get(i).getPadding();
                        sequenceManage.createSeq(seqlist.get(i), true);
                    }
                }
            }
            return sequenceManage.getNextNumByStr(tabName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    public Object getKey(String tabName) throws Exception {
//        try {
//            if(EsbUtil.getSeqmap().get(conId)==null){
//                EsbUtil.getSeqmap().put(conId, 1);
//                int len=seqlist.size();
//                for(int i=0; i<len; i++){
//                    Sequence sequence=new Sequence();
//                    sequence.setCode(seqlist.get(i).getTableId());
//                    sequence.setName(seqlist.get(i).getTableName());
//                    sequence.setPadding(seqlist.get(i).getPadding());
//                    sequence.setPrefix(seqlist.get(i).getPrefix());
//                    sequence.setSuffix(seqlist.get(i).getSuffix());
//                    GeneratorUtil.addSequence(sequence);
//                    if(tabName.equals(seqlist.get(i).getTableName())){
//                        padding=seqlist.get(i).getPadding();
//                    }
//                }
//            }
//           Sequence s=GeneratorUtil.getSequence(tabName);
//           return PubToolUtil.prefixStr0(PubToolUtil.castToString(s.getNumberNext()), padding);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }
}
